package com.wenc.psi.rpstr;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import androidx.annotation.NonNull;
import androidx.lifecycle.MutableLiveData;
import com.wenc.psi.dao.PartDao;
import com.wenc.psi.pojo.Part;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;


public class PartRepository {
    private final PartDao partDao;
    private MutableLiveData<List<Part>> partLive;
    private List<Part> partList;

    // 构造方法
    public PartRepository(Context context) {
        partDao = new PartDao();
        partLive = new MutableLiveData<>();
        // 获取所有part数据
        getAllPart();
    }

    public List<Part> getPartList() {
        return partList;
    }

    public MutableLiveData<List<Part>> getPartLive() {
        return partLive;
    }

    private final Handler handler = new Handler(Looper.myLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 200) {
                partList = (List<Part>) msg.obj;
                partLive.setValue(partList);
            } else if (msg.what == 400) {
                System.out.println("获取不到数据");
            }
        }
    };

    // 查询所有数据
    public void getAllPart() {
        new Thread(() -> {
            Message message = new Message();
            List<Part> parts = partDao.getAllData();
            if (parts != null) {
                message.what = 200;
                message.obj = parts;
            } else {
                message.what = 400;
            }
            handler.sendMessage(message);
        }).start();
    }

    public void getDataBySearch(String input){
        new Thread(() -> {
            Message message = new Message();
            List<Part> parts = partDao.getDataBySearch(input);
            if (parts != null) {
                message.what = 200;
                message.obj = parts;
            } else {
                message.what = 400;
            }
            handler.sendMessage(message);
        }).start();
    }

    // 插入
    public void insert(Part... parts) {
        // 插入操作
        partDao.insert(parts);
        // 获取数据
        getAllPart();
    }

    // 删除
    public void delete(Part... parts) {
        // 删除操作
        partDao.delete(parts);
        // 获取数据
        getAllPart();
    }

    // 更新
    public void update(Part oldP, Part newP) {
        // 更新操作
        partDao.update(oldP, newP);
        // 获取数据
        getAllPart();
    }

    public void clear(){
        System.out.println("clear");
//        List<Part> parts = new ArrayList<>(partLive.getValue());
        List<Part> parts = partLive.getValue();
        parts.clear();
        partLive.setValue(parts);
    }

}
